from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from app import models, schemas
from typing import List, Optional

class ConfigRepository:
    @staticmethod
    async def create_config(db: Session, config: schemas.ConfigCreate) -> models.Config:
        db_config = models.Config(**config.dict())
        db.add(db_config)
        db.commit()
        db.refresh(db_config)
        return db_config

    @staticmethod
    async def get_configs(db: Session, skip: int = 0, limit: int = 100) -> List[models.Config]:
        return db.query(models.Config).offset(skip).limit(limit).all()

    @staticmethod
    async def get_config(db: Session, config_id: int) -> Optional[models.Config]:
        return db.query(models.Config).filter(models.Config.id == config_id).first()

    @staticmethod
    async def update_config(db: Session, config_id: int, config: schemas.ConfigCreate) -> Optional[models.Config]:
        try:
            db_config = db.query(models.Config).filter(models.Config.id == config_id).first()
            if db_config:
                for key, value in config.dict().items():
                    setattr(db_config, key, value)
                db.commit()
                db.refresh(db_config)
            return db_config
        except IntegrityError:
            db.rollback()
            raise ValueError("配置更新失败")

    @staticmethod
    async def toggle_config(db: Session, config_id: int) -> Optional[models.Config]:
        """切换配置的启用状态"""
        db_config = db.query(models.Config).filter(models.Config.id == config_id).first()
        if db_config:
            db_config.enabled = not db_config.get_enabled()
            db.commit()
            db.refresh(db_config)
        return db_config

    @staticmethod
    async def get_enabled_configs(db: Session) -> List[models.Config]:
        """获取所有启用的配置，如果没有则返回默认配置"""
        enabled_configs = db.query(models.Config).filter(models.Config.enabled == True).all()
        if not enabled_configs:
            # 如果没有启用的配置，返回一个默认配置
            default_config = models.Config(
                name="默认配置",
                type="qbittorrent",
                host="localhost",
                port=8080,
                username="admin",
                password="adminadmin",
                enabled=True
            )
            return [default_config]
        return enabled_configs

    @staticmethod
    async def delete_config(db: Session, config_id: int) -> bool:
        db_config = db.query(models.Config).filter(models.Config.id == config_id).first()
        if db_config:
            db.delete(db_config)
            db.commit()
            return True
        return False
